<?php

namespace backend\modules\wxad\controllers;

use backend\modules\base\controllers\BaseController;
use Yii;
use backend\modules\wxad\models\WxAd;
use backend\modules\wxad\models\search\WxAdSearch;
use yii\base\Exception;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * WxadController implements the CRUD actions for WxAd model.
 */
class WxadController extends BaseController
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all WxAd models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new WxAdSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single WxAd model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new WxAd model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new WxAd();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['update', 'id' => $model->rec_id,
                'FormPage'=>'FormPage01']);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing WxAd model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $FormPage = isset($_GET['whiceForm'])?$_GET['whiceForm']:'FormPage01';

        $post = Yii::$app->request->post();
         unset($post['WxAd']['ad_images']);
        if ($model->load($post) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->rec_id]);
        } else {
            return $this->render('update', [
                'model' => $model,
                'FormPage'=>$FormPage
            ]);
        }
    }

    /**
     * Deletes an existing WxAd model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the WxAd model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return WxAd the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = WxAd::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    /**
     * 广告图片上传
     * @throws \yii\db\Exception
     */
    public function actionAdupload()
    {
        if($_FILES==null){
            echo  json_encode([]);exit;
        }
        $postData = Yii::$app->request->post();
        $baseUrl = Yii::$app->basePath;
        $rec_id = $postData['rec_id'];

        $webUrlBaseOnApp= '/web/images/wxad/wxad/';
        $baseImages = $baseUrl.$webUrlBaseOnApp;
        is_dir($baseImages) OR mkdir($baseImages, 0777, true);

        $sourceImg = $_FILES['WxAd']['tmp_name']['ad_images'];
        $imageName = time().'-'.rand(10,1000).'.png';

        $objImage = $baseImages.$imageName;

        //
        $connection = Yii::$app->db;
        $transaction = $connection->beginTransaction();
        try{
            if(move_uploaded_file($sourceImg,$objImage)){
                $ad_images  = $webUrlBaseOnApp.$imageName;
                $WxAd = WxAd::findOne([$rec_id]);
                $WxAd->ad_images = $ad_images;
                if(!$WxAd->save()) {
                    throw new Exception(json_encode($WxAd->errors));
                }
//                Goods::SortingImages($goods_id);
                $transaction->commit();
                return json_encode(array(true,[]));
            }else{
                throw new Exception(json_encode('文件上传失败！'));
            }
        }catch (Exception $e){
            $transaction->rollBack();
            print_r($e->getMessage());exit;
        }

    }
}
